/*
 * Module 02
 *
 */

package ua.gl.basecamp.tabachnyy.util;

import ua.gl.basecamp.tabachnyy.testcase.Answer;
import ua.gl.basecamp.tabachnyy.testcase.Question;
import ua.gl.basecamp.tabachnyy.testcase.UserAnswer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yaroslav.tabachnyy@gmail.com
 * @version 1.02
 * @date 14.02.2013
 *
 */
public class UserAnswersParser {

    private static final String COMMA_WITH_OPTIONAL_SPACE = ",(\\s)*";

    private String answersString;

    public UserAnswersParser(String answersString) {
        this.answersString = answersString;
    }

    public List<UserAnswer> getAnswersByStrings() {
        String[] answers = answersString.split(COMMA_WITH_OPTIONAL_SPACE);
        List<UserAnswer> answersByStrings = new ArrayList<UserAnswer>();

        for (String answerString : answers) {
            answersByStrings.add(new UserAnswer(answerString));
        }
        return answersByStrings;
    }

    public List<UserAnswer> getAnswersByNumbers(Question question) {
        List<UserAnswer> answersByNumbers = new ArrayList<UserAnswer>();

        for (int answerNumber : parseAnswerNumbers()) {
            /*
             *  To get corresponding answer from list we must use (answerNumber - 1),
             *  'cause user question numeration starts from 1 (not 0!)
             */
            String answerString =
                    question.getAnswer(answerNumber - 1).getStringRepresentation();
            answersByNumbers.add(new UserAnswer(answerString));
        }
        return answersByNumbers;
    }

    private int[] parseAnswerNumbers() {
        String[] answerStrings = answersString.split(COMMA_WITH_OPTIONAL_SPACE);

        int[] answerNumbers = new int[answerStrings.length];

        for (int index = 0; index < answerNumbers.length; index++) {
            answerNumbers[index] = Integer.parseInt(answerStrings[index]);
        }
        return answerNumbers;
    }
}
